package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    /*
    文件上传处理
    */
    @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<Object> upload(MultipartFile file) {
        try {
            //1. 设置文件的名称: uuid + 原始文件的后缀
            String originalFilename = file.getOriginalFilename();//原始文件名有后缀
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); //获取原始文件的后缀
            String fileName = UUID.randomUUID() + suffix;

            //2. 指定保存的目录
            File baseFile = new File(basePath);
            //判断目录是否存在，如果不存在，新建
            if (!baseFile.exists()) {
                baseFile.mkdirs();
            }
            //3.保存临时文件，转存到本地目录
            file.transferTo(new File(basePath + fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    /**
     * 文件下载
     * @param name 文件名称
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //1. 获取输入流
            FileInputStream fis = new FileInputStream(basePath + name);
            //2. 获取输出流
            ServletOutputStream os = response.getOutputStream();
            //3. 设置响应头
            response.setContentType("image/jpeg");
            //4.循环读写
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
                os.flush();
            }
            //5.关闭流
            os.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
